using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace SampleWebParts
{
  public class RSSViewer : WebPart
  {
    private string rssUrl = "";
    [WebBrowsable(true)]
    [Personalizable(PersonalizationScope.Shared)]
    [WebDescription("URL for RSS feed to be displayed")]
    public string RSSUrl
    {
      get { return rssUrl; }
      set { rssUrl = value; }
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
      try
      {
        XmlDocument rssDoc = new XmlDocument();
        XmlTextReader xRead = new XmlTextReader(rssUrl);
        rssDoc.Load(xRead);

        writer.WriteFullBeginTag("h1");
        HyperLink titlelink = new HyperLink();
        titlelink.Text = rssDoc.SelectSingleNode("./rss/channel/title").InnerText;
        titlelink.NavigateUrl = rssDoc.SelectSingleNode("./rss/channel/link").InnerText;
        titlelink.RenderControl(writer);
        writer.Write(rssDoc.SelectSingleNode("./rss/channel/title").InnerText);
        writer.WriteEndTag("h1");
        writer.WriteLine();
        writer.WriteLine(rssDoc.SelectSingleNode("./rss/channel/description").InnerText + "<br />");

        XmlNodeList xItems = rssDoc.SelectNodes("./rss/channel/item");
        foreach (XmlNode xItem in xItems)
        {
          string urlLink = xItem.SelectSingleNode("./link").InnerText;
          HyperLink hyperlink = new HyperLink();
          hyperlink.Text = xItem.SelectSingleNode("./title").InnerText;
          hyperlink.NavigateUrl = urlLink;
          hyperlink.RenderControl(writer);
          writer.WriteBreak();
          writer.WriteLine();
        }
      }
      catch (Exception ex)
      {
        writer.WriteLine("<h4>Feed not available: " + ex.Message + "</h4>");
      }
    }
  }
}
